const { db, query } = require('../database/db')
class Role {
    static findByPk(id) {
        let sql = `
            SELECT * FROM roles WHERE id = ?
        `
        return query(sql, [id])
    }
    static create(created_at, name, description, role_code) {
        let sql = `
            INSERT INTO Roles (name, description, created_at,role_code) VALUES (?, ?, ?,?)
        `
        return query(sql, [name, description, created_at, role_code])
    }
    // 删除角色---真删除
    static delete_t(id) {
        let sql = `DELETE FROM roles WHERE id = ?`
        return query(sql, id)
    }
    // 角色的列表搜索列表--分页
    static role_list = async (name, page_size, page) => {
        let listSql = `SELECT * FROM roles`;
        let countSql = `SELECT COUNT(*) as count FROM roles`;
        let params = [];
        let conditions = [];

        if (name) {
            conditions.push(`name LIKE ?`);
            params.push(`%${name}%`);
        }

        // 添加WHERE条件（如果有）
        if (conditions.length > 0) {
            const whereClause = ` WHERE ${conditions.join(' AND ')}`;
            listSql += whereClause;
            countSql += whereClause;
        }

        // 添加分页（仅对列表查询）
        listSql += ` LIMIT ? OFFSET ?`;
        params.push(page_size);
        params.push((page - 1) * page_size);

        try {
            const [rolesResult, countResult] = await Promise.all([
                query(listSql, params),
                query(countSql, params.slice(0, -2)) // 总数查询不需要分页参数
            ]);

            return {
                roles: rolesResult,
                total: countResult[0].count // 假设countResult返回的是[{count: 123}]
            };
        } catch (error) {
            console.error('查询失败:', error);
            throw error;
        }
    };
    // 角色的修改--set数据
    static edit_set = (id, name, description, updatetime) => {
        let sql = `UPDATE roles SET name = ?, description = ?, updatetime = ? WHERE id= ?`
        // 传数据的时候，注意数组的顺序，一一对应
        return query(sql, [name, description, updatetime, id])
    }

    // 获取角色的所有权限
    static permission_get = (role_id) => {
        let sql = `
            SELECT p.permission_code, p.id, p.name 
            FROM permissions p
            JOIN rolepermissions rp ON rp.permission_id = p.id
            JOIN roles r ON rp.role_id = r.id
            WHERE r.id = ?
        `;
        return query(sql, [role_id]);
    }
    // 角色的权限设置
    static expression_set = (role_id, expression_ids) => {
        const sql = `INSERT INTO rolepermissions (role_id, permission_id) VALUES (?, ?)`;
        return Promise.all(
            expression_ids.map(item =>
                query(sql, [role_id, Number(item)])
            )
        )
    };
    // 获取全部角色
    static all_role() {
        let sql = `
            SELECT roles.id,roles.name
            FROM roles
        `
        return query(sql)
    }
}

module.exports = Role